<?php

class MarketingUtility
{
    public static function runCampaign($campaignId, $listId, $test = 1)
    {
        $dataDir = Yii::getPathOfAlias('application.data.marketing').'/'.$campaignId;
        $subject = trim(file_get_contents($dataDir.'/subject.txt'));
        $view = 'marketing/'.$campaignId;
        if($test == 1)
        {
            $email = 'huynhphan89@gmail.com';
            //$email = 'camtu@likevn.com';
            //$email = 'kelly.nguyen2802@gmail.com';
            $data = array('campaignId' => $campaignId, 'email' => $email);
            $success = (int) MailUtility::send($email, $subject, $view, $data);
            echo $email.'|'.$success."\n";
            return;
        }

        $counter = 0;
        $file = fopen($dataDir.'/'.$campaignId.'_'.str_pad($listId, 3, '0', STR_PAD_LEFT).'.txt', 'r');
        while(!feof($file))
        {
            $email = trim(fgets($file));
            if(filter_var($email, FILTER_VALIDATE_EMAIL) === false)
            {
                echo ++$counter.': '.$email."|Invalid\n";
                continue;
            }

            $data = array('campaignId' => $campaignId, 'email' => $email);
            $success = (int) MailUtility::send($email, $subject, $view, $data);
            echo ++$counter.': '.$email.'|'.$success."\n";
        }
    }

    public static function splitEmails($campaignId, $numLinePerFile)
    {
        $input = fopen(Yii::getPathOfAlias('application.data.marketing').'/'.$campaignId.'/'.$campaignId.'.txt', 'r');
        $counter = 0;
        while(!feof($input))
        {
            // read line
            $email = trim(fgets($input));
            if(filter_var($email, FILTER_VALIDATE_EMAIL) === false)
            {
                continue;
            }

            // write line
            if($counter % $numLinePerFile == 0)
            {
                if(isset($output))
                {
                    fclose($output);
                }
                $listId = intval(($counter/$numLinePerFile)+1);
                $file = $campaignId.'_'.str_pad($listId, 3, '0', STR_PAD_LEFT).'.txt';
                $output = fopen(Yii::getPathOfAlias('application.data.marketing').'/'.$campaignId.'/'.$file, 'w');
            }
            fwrite($output, $email."\n");
            $counter++;
        }
        @fclose($output);
    }

    public static function openEmail($campaignId, $email)
    {
        MarketingModel::openEmail($campaignId, $email);
    }
}
